package edu.ynu.se.xiecheng.achitectureclass.auth.controller;

import edu.ynu.se.xiecheng.achitectureclass.auth.dao.UserDAO;
import edu.ynu.se.xiecheng.achitectureclass.auth.dto.RegisterRequest;
import edu.ynu.se.xiecheng.achitectureclass.auth.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.HashSet;

@Api(tags = "认证管理")
@RestController
@RequestMapping("/api/auth")
@CrossOrigin(originPatterns = "*", allowCredentials = "true")
public class AuthController {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation("登录")
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String username, @RequestParam String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        
        try {
            subject.login(token);
            // 获取会话并存储用户信息
            Session session = subject.getSession();
            session.setAttribute("username", username);
            
            String sessionId = session.getId().toString();
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("data", Map.of(
                "token", sessionId,
                "username", username
            ));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "登录失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    @ApiOperation("登出")
    @PostMapping("/logout")
    public ResponseEntity<?> logout() {
        SecurityUtils.getSubject().logout();
        return ResponseEntity.ok("登出成功");
    }

    @ApiOperation("检查登录状态")
    @GetMapping("/status")
    public ResponseEntity<?> checkLoginStatus() {
        Subject subject = SecurityUtils.getSubject();
        Map<String, Object> result = new HashMap<>();
        result.put("isAuthenticated", subject.isAuthenticated());
        if (subject.isAuthenticated()) {
            result.put("username", subject.getPrincipal());
        }
        return ResponseEntity.ok(result);
    }

    @ApiOperation("注册")
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequest request) {
        // 检查用户名是否已存在
        if (userDAO.findByUsername(request.getUsername()).isPresent()) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "用户名已存在");
            return ResponseEntity.badRequest().body(error);
        }

        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword())); // 加密密码
        user.setName(request.getName());
        user.setRoles(new HashSet<>()); // 初始化一个空的角色集合

        // 保存用户
        userDAO.save(user);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "注册成功");
        return ResponseEntity.ok(result);
    }
} 